/**
 *  Copyright (C) 2014-2015 The MeiRiQ All Right Reserve.
 */
package com.example.bannerdemo.view;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.example.bannerdemo.R;

/**
 * Banner显示View
 * 
 * @version 1.0
 * @time 2015-6-8 下午8:53:45
 * @author zhangchaoxian@meiriq.com
 */
public class BannerView extends FrameLayout {
	// 定时执行任务
	private ScheduledExecutorService executorService;
	private ScheduledFuture<?> futureTask;
	// 自动播放间隔时间
	private final int INTERVAL_TIME = 1000;

	/** 用于左右滑动的容器 */
	private ViewPager mViewPager = null;
	/** banner数据适配器 */
	private BannerAdapter mAdapter = null;
	// 放置圆点
	private LinearLayout mDotContainer = null;
	// 当前轮播页
	private int mCurrentPage = 0;

	public BannerView(Context context) {
		super(context);
		initView();
	}

	public BannerView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView();
	}

	public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initView();
	}

	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
	public BannerView(Context context, AttributeSet attrs, int defStyleAttr,
			int defStyleRes) {
		super(context, attrs, defStyleAttr, defStyleRes);
		initView();
	}

	// 初始化View设置
	private void initView() {
		executorService = Executors.newSingleThreadScheduledExecutor();

		mViewPager = new ViewPager(getContext());
		mViewPager.setFocusable(true);
		mViewPager.setPageMargin(5);
		mViewPager.setBackgroundColor(Color.BLUE);
		mViewPager.setOnTouchListener(mTouchListener);
		mViewPager.setOnPageChangeListener(new MyPageChangeListener());
		LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		addView(mViewPager, layoutParams);

		// 小圆点容器
		mDotContainer = new LinearLayout(getContext());
		mDotContainer.setGravity(Gravity.CENTER);
		mDotContainer.setOrientation(LinearLayout.HORIZONTAL);// 水平排布
		LayoutParams layoutParams2 = new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		layoutParams2.bottomMargin = 10;
		// 底部，水平居中
		layoutParams2.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;

		addView(mDotContainer, layoutParams2);
	}

	/** 生成小圆点 */
	private void creatDot(int count) {
		// 先移除以前所有的子View
		mDotContainer.removeAllViews();
		for (int i = 0; i < count; i++) {
			View dot = new View(getContext());
			dot.setBackgroundResource(R.drawable.selector_dot_state);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					15, 15);
			params.setMargins(5, 5, 5, 5);
			mDotContainer.addView(dot, params);
		}
		// 将第一个选中
		selectDotView(0);
	}

	/**
	 * 改变小圆点的状态
	 * 
	 * @param pos
	 *            被激活的小圆点
	 */
	private void selectDotView(int pos) {
		// 全部不选中状态
		for (int i = 0; i < mDotContainer.getChildCount(); i++) {
			mDotContainer.getChildAt(i).setSelected(false);
		}
		// 不为 空情况下设置为选中状态
		if (mDotContainer.getChildAt(pos) != null) {
			mDotContainer.getChildAt(pos).setSelected(true);
		}
	}

	/**
	 * 通知banner 数据改变了
	 */
	public void notifyDataSetChanged() {
		stopPlay();
		// mViewPager.removeAllViews();
		mAdapter.notifyDataSetChanged();
		// 重新创建小圆点
		creatDot(mAdapter.getCount());
		// 从0开始
		mViewPager.setCurrentItem(0, false);
		// auto start
		autoPlay();
	}

	/**
	 * 绑定banner数据的适配器
	 * 
	 * @param adapter
	 */
	public void setAdapter(BannerAdapter adapter) {
		mAdapter = adapter;
		mViewPager.setAdapter(mAdapter);
	}

	// 开始自动播放
	private void autoPlay() {
		// 指定时间内执行一次任务
		futureTask = executorService.schedule(mScrollTask, INTERVAL_TIME,
				TimeUnit.MILLISECONDS);
		// futureTask = executorService.scheduleWithFixedDelay(mScrollTask,
		// INTERVAL_TIME, INTERVAL_TIME, TimeUnit.MILLISECONDS);
	}

	// 停止自动播放
	private void stopPlay() {
		if (futureTask == null) {
			return;
		}
		futureTask.cancel(true);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			mViewPager.setCurrentItem(mCurrentPage, true);
		};
	};

	private Runnable mScrollTask = new Runnable() {

		@Override
		public void run() {
			mCurrentPage = (mCurrentPage + 1) % mAdapter.getCount();
			mHandler.obtainMessage().sendToTarget();
		}
	};

	private OnTouchListener mTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				System.out.println("down");
				break;
			case MotionEvent.ACTION_UP:
				System.out.println("up");
				break;

			default:
				break;
			}
			return false;
		}
	};

	/** ViewPager的监听器 当ViewPager中页面的状态发生改变时调用 */
	private class MyPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			switch (state) {
			// 空闲状态
			case ViewPager.SCROLL_STATE_IDLE:
				System.out.println("idle..");
				autoPlay();
				break;
			// 手动去滑动状态
			case ViewPager.SCROLL_STATE_DRAGGING:
				System.out.println("dragging");
				// 手动滑动时，不给自动滚动
				stopPlay();
				break;
			// 滑动完毕,固定下来
			case ViewPager.SCROLL_STATE_SETTLING:
				System.out.println("settling");

				break;
			default:
				break;
			}

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int pos) {
			selectDotView(pos);
			mCurrentPage = pos;
		}
	}
}
